package Linux五种IO模型.reactor2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author coderFu
 * @create 2022/3/8
 */
public class ReactorDemo2 {

    private Selector selector;

    public ReactorDemo2(int port){
        // 在这里面完成初始化
        // 四部曲
        try{
            selector = Selector.open();

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.configureBlocking(false);

            serverSocketChannel.bind(new InetSocketAddress(port));

            SelectionKey register = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            // 将AcceptorDemo2 对象附带进去
            register.attach(new AcceptorDemo2(selector,serverSocketChannel));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run(){

        try{
            while ( !Thread.interrupted()){
                // 在程序没有被中断之前，一直运行，监听状态

                if (selector.select() == 0){
                    continue; // 如果没有事件就绪，就阻塞在这里
                }
                // 获取所有就绪的key
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                if (iterator.hasNext()){
                    // 将就绪的key交给转发去处理
                    dispatch(iterator.next());
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void dispatch(SelectionKey key){

        // 根据客户端与服务端附带的不同的对象来执行不同的内容
        Runnable attachment = (Runnable) key.attachment();

        if (attachment != null){
            attachment.run();
        }

    }
}
